//
//  HomeVIewController.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/17.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift
import Reachability
import SVProgressHUD


class HomeViewController: ViewController {
    
    private var categroy: FeedsCategory!
    
    private lazy var emptyView: HomeEmptyView? = {
        let v = HomeEmptyView()
        _ = v.didTapSubject.subscribe(onNext: { [weak self] (emptyView) in
            guard let self = self else { return }
            emptyView.showFetchingMessage()
            self.fetchData()
        })
        return v
    }()
    
    private lazy var pageTitle: PageTitleView = {
        let v = PageTitleView(titles: categroy.categories.map{$0.title}, style: PageTitleStyle())
        _ = v.itemDidTapSubject.subscribe(onNext: { [weak self] (item) in
            guard let self = self else { return }
            self.pageContent.autoScrollTo(item.index)
            let vc = self.feedVcs[item.index]
            vc.isFetchData = true
        })
        return v
    }()
    
    private lazy var pageContent: PageContentView = {
        let v = PageContentView(childs: feedVcs, parent: self)
        _ = v.scrollIndexSubject.subscribe(onNext: { [weak self] scrollToIndex in
            self?.pageTitle.selectedIndex = scrollToIndex
        })
        _ = v.willDisplaySubject.subscribe(onNext: { [weak self] indexs in
            guard let self = self else { return }
            let leftVc = self.feedVcs[indexs.left]
            leftVc.isFetchData = true
            let rightVc = self.feedVcs[indexs.right]
            rightVc.isFetchData = true
        })
        return v
    }()
    
    private var feedVcs: [FeedsViewController] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        fetchData()
    }
}

private extension HomeViewController {
    func fetchData() {
        guard Network.isReachable else {
            emptyView?.showErrorMessage("网络不可用，检查网络后点击重试...")
            return
        }
        _ = Network.fetchCategory()
            .preDo(onNext: { (model) in
                SVProgressHUD.show()
                MemoryCache.default.set(value: model, for: MemoryCache.feedCategoryKey)
            })
            .observeOn(MainScheduler.asyncInstance)
            .subscribe(onNext: { (model) in
                SVProgressHUD.dismiss()
                self.removeEmpty()
                self.categroy = model
                self.feedVcs = self.categroy.categories.map(FeedsViewController.init(categoryItem:))
                self.setupCotents()
                if let first = self.feedVcs.first {
                    first.isFetchData = true
                }
            }) { [weak self] (error) in
                SVProgressHUD.dismiss()
                guard let self = self, let emptyView = self.emptyView else { return }
                #if DEBUG
                emptyView.showErrorMessage(error.localizedDescription)
                #else
                emptyView.showErrorMessage()
                #endif
            }
    }
    
    func setupUI() {
        view.backgroundColor = .commonBackgroundColor
        guard let emptyView = emptyView else { return }
        view.addSubview(emptyView)
        emptyView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
    
    func removeEmpty() {
        emptyView?.removeFromSuperview()
        emptyView = nil
    }
    
    
    func setupCotents() {
        view.addSubview(pageTitle)
        pageTitle.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.top).inset(44)
        }
        view.addSubview(pageContent)
        pageContent.snp.makeConstraints { (make) in
            make.top.equalTo(pageTitle.snp.bottom)
            make.left.bottom.right.equalToSuperview()
        }
    }
}
